<script setup>
import LayoutNav from '../Layout/components/LayoutNav.vue';
import LayoutFooter from '../Layout/components/LayoutFooter.vue';
import router from '@/router';
import { useRoute } from 'vue-router';
import { onMounted, ref } from 'vue';
import { getUserInfoApi } from '@/api/user';
import { getHistoryAPI } from '@/api/message';
import { useTokenStore } from '@/store/token';

const route = useRoute()
console.log(route.params);

function getShopInfo() {
  getUserInfoApi(route.params.userId).then(res => {
    if (res.code === 0) {
      console.log(res.data)
      user.value.id = res.data.userId;
      user.value.name = res.data.username;
      user.value.avatar = res.data.avatar;
    }
  })
}
getShopInfo();

// 用户信息
const tokenStore = useTokenStore()

// 获取聊天对象用户id
import { useMessageStore } from '@/store/modules/message'
const messageStore = useMessageStore();

// 导入 SockJS 库
import SockJS from 'sockjs-client';
const baseUrl = 'http://localhost:8081/taoxi';

const user = ref({
  id: '',
  name: '',
  avatar: ''
});
const avatar = ref('');
// 消息列表
const msgList1 = ref([]); // 我发送的消息
const msgList2 = ref([]); // 对方发送的消息
const msgList = ref([]);  // 消息列表
const sortedMsgList = ref([]);  // 排序后的消息列表

const message = ref({
  name: '',
  time: null,
  to:'',
  content:''
})

// 获取当前用户的聊天对象id
const othersId = ref([])

// 定义聊天对象列表
const userIds = ref([])
// 定义websocket连接
let socket = null;
//初始化 WebSocket 连接
const init = () => {
  socket = new SockJS(`${baseUrl}/chat?userId=${user.value.id}`);
  if (socket !== null) {
    console.log("socket已存在"+socket);
  }
  //打开事件
  socket.onopen = function () {
    console.log("websocket已打开");
  };
  //浏览器端收消息，获取从服务端发送过来的文本消息
  socket.onmessage = function (msg) {
    // 接收消息
    // console.log("收到消息：" + msg.data);
    const messages = JSON.parse(msg.data);
    // 使用 Set 去重并收集 fromUserId
    const uniqueUserIds = new Set(
      messages.map(message => message.fromUserId)
    );

    // 将去重后的 fromUserId 存入 othersId
    othersId.value = Array.from(uniqueUserIds);
    userIds.value = [...new Set(othersId.value)]
    messageStore.setUserIds(userIds.value);
    console.log("userIds:", messageStore.userIds);
  };
  //关闭事件
  socket.onclose = function () {
    console.log("Websocket 已关闭");
  };
  //发生错误事件
  socket.onerror = function () {
    console.log("Websocket发生了错误");
  };
}
// 获取用户信息
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus';
import { onBeforeRouteLeave } from 'vue-router';

const userStore = useUserStore();
 
onMounted(() => {
  user.value.id = tokenStore.user.userId;
  user.value.name = userStore.nickname
  console.log(user.value);
  // user.value = JSON.parse(localStorage.getItem('user'))
  init()
})

// 获取用户信息
const userInfos = ref([])
const usersInfo = ref([])
// 获取当前用户的聊天对象列表

function getChatList() {
  for (let i = 0; i < messageStore.userIds.length; i++) {
    const userInfo = getUserInfoApi(5) //messageStore.userIds[i]
    userInfos.value.push(userInfo)
  }
  console.log(userInfos.value);
  // 使用 Promise.all 等待所有 Promise 解析完成
  Promise.all(userInfos.value).then(results => {
    // results 是一个数组，包含每个 Promise 解析后的值
    // 使用 map() 提取每个 result 的 data 字段并组成新的数组
    const dataArray = results.map(result => result.data);
    // 输出新的数组
    console.log(dataArray);
    usersInfo.value.push(dataArray[1][0])
    // for (let i = 0; i < dataArray.length; i++) {
    //   usersInfo.value.push(dataArray[i][0])
    // }
    console.log(usersInfo.value);
  }).catch(error => {
    console.error("Error waiting for promises:", error);
  });

}
getChatList();

// 点击状态
const selectedChat = ref(null)

// 获取不同对象的消息
const selectChat = (userId) => {
  // 获取历史消息
  console.log('当前用户，聊天对象：',user.value.id, userId)
  getHistoryAPI(1, userId, 1).then(res => {
    if (res.code === 0) {
      msgList1.value = res.data
      console.log(msgList1.value);
    }
  })
  getHistoryAPI(userId, 1, 1).then(res => {
    if (res.code === 0) {
      msgList2.value = res.data
      console.log(msgList2.value);
    }
  })
  // 合并两个数组
  const msgList1Array = [];
  for (const item of msgList1.value) {
    msgList1Array.push(item);
  }

  const msgList2Array = [];
  for (const item of msgList2.value) {
    msgList2Array.push(item);
  }
  msgList.value = [...msgList1Array, ...msgList2Array];
  console.log(msgList.value);
  
  // 对合并后的数组按 createTime 进行排序
  sortedMsgList.value = msgList.value.sort((a, b) => {
    // 按 createTime 字段进行升序排序，时间越早的排前面
    return new Date(a.createTime) - new Date(b.createTime);
  });
  console.log(sortedMsgList.value);

  selectedChat.value = userId;

}

const send = () => {
  // 发送消息
  if (!message.value.content) {
    ElMessage.warning('请输入内容');
    return
  }

  const messages = {
    fromUserId: user.value.id,
    toUserId: selectedChat.value,
    content: message.value.content,
    msgType: 1,
    goodsId: 1
  };
  console.log(messages);
  try {
    socket.send(JSON.stringify(messages));
  } catch (error) {
    ElMessage.warning(`发送失败: ${error.message}`, false);
  }
  message.value.content = ''
}

// 刷新
const refresh = () => {
  selectChat(selectedChat.value)
}

// 断开连接
onBeforeRouteLeave(() => {
  socket.close()
  socket.onclose = function () {
    console.log("Websocket 已关闭");
  };
  socket = null;
})


</script>
<template>
  <LayoutNav/>
  <div class="container">
    <!-- 头部信息栏 -->
    <div class="header">
      <div class="back"><span @click="router.back();">
        <i class="iconfont icon-angle-left"></i>
        <i class="iconfont icon-angle-left"></i>
        返回商品页面
      </span></div>
      <div class="shop-contain" v-bind="user">
        <el-avatar :size="50" :src="user.avatar" />
        {{ user.name }}
      </div>
    </div> 
    <!-- 聊天界面 -->
    <div class="main">
      <div class="side">
        <div class="chat-list">
          <!-- 桃禧服装店 -->
          <div
            class="chat-item"
            v-for="(chat, index) in usersInfo"
            :key="index"
            @click="selectChat(chat.userId)"
            :class="{ 'selected': selectedChat === chat.userId }"
          >
            <img :src="chat.avatar" alt="Avatar" class="avatar" />
            <span class="chat-name">{{ chat.username }}</span>
          </div>
        </div>
      </div>
      <div class="chat-box">
        <p>聊天界面</p>
        <div v-for="(item, index) in sortedMsgList" :key="index" class="message">
          <div class="right" v-if="item.fromUserId == user.id"> 
            <div class="content">{{ item.content }}</div>
            <div class="time">{{ item.createTime }}</div>
          </div>
          <div class="left" v-else>
            <div class="content">{{ item.content }}</div>
            <div class="time">{{ item.createTime }}</div>
          </div>
        </div>
        <div class="input-box">
          <el-input type="textarea" v-model="message.content" :autosize="{ minRows: 2, maxRows: 5}" placeholder="请输入聊天内容"></el-input>
          <el-button type="primary" @click="send(message.content)">发送</el-button>  
          <el-button type="primary" @click="refresh()" style="margin-right: -50px;">刷新</el-button>    
        </div>
      </div>
    </div>
  </div>
  <LayoutFooter/>
</template>

<style scoped lang='scss'>
.header{
  background: 100%;
  width: 100%;
}
.main {
  display: flex;
  background: #fff;
  height: 600px;
  // height: 100vh;
}

.chat-box {
  display: flex;
  height: 600px;
  border-radius: 5px;
  overflow: hidden;
}


.side {
  width: 250px;
  background-color: #f4f4f4;
  padding: 20px;
  border-right: 1px solid #ddd;

  .chat-list {
    display: flex;
    align-items: center;
    padding: 10px 0;
    background-color: #fff;
    border-bottom: 1px solid #ddd;

    .chat-item {
      display: flex;
      align-items: center;
      padding: 8px;
      margin-bottom: 10px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      cursor: pointer;
      width: 100%; /* 使聊天项占满一整行 */
    }

    .chat-item.selected {
      background-color: #e58686; /* 修改为选中时的背景颜色 */
    }

    .chat-item:hover {
      background-color: #f0f0f0;
    }

    .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
  }

  .chat-name {
    font-size: 16px;
    font-weight: bold;
  }
  }
}

.chat-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow: auto;
  position: relative;
  overflow-y: auto; /* 添加滚动条 */
  
  .message {
    display: flex;
    margin-bottom: 10px;
    justify-content: space-between;
  }
  
  .left {
    align-self: flex-start;
    margin-right: auto; /* 推到左边 */
  }

  .right {
    align-self: flex-end;
     margin-left: auto; /* 推到右边 */
  }
  
  .content {
    max-width: 500px;
    padding: 10px;
    border-radius: 10px;
    background-color: #e6f7ff;
    word-break: break-all;
  }

  .time {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }

  
  .input-box{
    display: flex;
    position: absolute;
    bottom: 0;
    width: calc(100% - 40px);
    
    .el-button {
      width: 80px;
      margin-left: 20px;
    }
  }
}

</style>